import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, Link, browserHistory} from 'react-router';
import $ from 'jquery';
import Swiper from 'react-id-swiper';
// import DetailSlider from './DetailSlider.js';
import NowAuction from './NowAuction.js';
// import CarReport from './CarReport.js';
// detail slider
class DetailSlider extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      liked: props.liked,
      imageGroup: [],
      bindex: 0,
      isload: 0
    };
    // this.swiper = null;
    this.changeBannerIndex = this.changeBannerIndex.bind(this);
  }
  changeBannerIndex(e) {
    $(this).onDoubleClick();
    this.setState({
      bindex: $(e.target).data('idx')
    });
  }

  componentDidMount(){}

  componentWillMount() {}

  componentWillUpdate() {
    $(function() {
      $(".carpic-btn-group > a").click(function() {
        $(".carpic-btn-group > a").eq($(this).index()).addClass("active").siblings().removeClass("active");
      });
    });

    let that = this;
    $('.like-toggle').click(function(e) {
      e.preventDefault();
      if ($(this).hasClass('active')) {
        return;
      }
      $.ajax({
        type: "POST",
        url: CBH.apiRoot + "/?g=Api&m=User&a=like",
        data: {
          itemid: that.props.item.id,
          uid: CBH.UserInfo.id
        },
        dataType: 'jsonp',
        success: function(data) {
          that.setState({liked: data.result});
        }
      });
    });

    if (!this.state.isload) {
      $.ajax({
        type: "GET",
        url: CBH.apiRoot+'/?g=Api&m=Carport&a=img_group&type=jsonp',
        data: {
          cid: this.props.item.cpid
        },
        dataType: 'jsonp',
        success: function(res) {
          console.log(res);
          let imagesGroup = [];
          if (res.data.length) {
            //格式化车源图片分组信息
            for (var i = 0, len = res.data.length; i < len; i++) {
              //分组
              let imgObjs = res.data[i];
              let imgs = [];
              for (var j = 0, slen = imgObjs.data.length; j < slen; j++) {
                //图片字段分组合并
                imgs = imgs.concat(imgObjs.data[j].value.map((item) => {
                  return CBH.imgUploadPath + item;
                }));
              }
              imagesGroup[i] = {
                title: imgObjs.title,
                images: imgs
              };
            }
          }
          else {
            //无车源图片时，用常规图片替换
            if (this.props.ishave) {
              let imgs = [];
              for (var k = 0, leng = this.props.item.imageitems.length; k < leng; k++) {
                imgs[k] = CBH.imgUploadPath + this.props.item.imageitems[k].url;
              }
              imagesGroup[0] = {
                title: '车辆图片',
                images: imgs
              };
            }
          }
          this.setState({imageGroup: imagesGroup, isload: 1});
        }.bind(this)
      });
    }
  }



  render() {
    let style = {
      width: "400px",
      height: "300px"
    };

    const params = {
      pagination: '.swiper-pagination',
      // loop : true,
      nextButton: '.swiper-button-next',
      prevButton: '.swiper-button-prev',
      // onInit: (swiper) => {
      //   this.swiper = swiper;
      // }
    };

    //图片数组详情输出
    let listItemss = this.state.imageGroup.length > this.state.bindex
      ? (this.state.imageGroup[this.state.bindex].images.length
        ? this.state.imageGroup[this.state.bindex].images.map((image, i) => <div key={i}>
          <a href="javascript:;">
            <img style={style} className="slideImg" src={image} alt="pic"/>
          </a>
        </div>)
        : <div>
          <span>无图片!</span>
        </div>)
      : <div>
        <span>无图片!</span>
      </div>;

    //图片分组输出
    let that = this;
    let listImageGroup = this.state.imageGroup.map((item, keyValue) => <a href="javascript:;" onClick={that.changeBannerIndex} data-idx={keyValue} key={keyValue}>{item.title}</a>); //images
    let adwordArray = this.props.item.adwords
      ? this.props.item.adwords.split(',')
      : [];
    let adwordItems = adwordArray.map((word) => <span className="label label-success" key={word}>{word}</span>);
    return (
      <div>

        <Swiper {...params}>
          {listItemss}



        </Swiper>

        <div className='like'>
          <button className={'like-toggle two' + (this.state.liked
            ? ' active'
            : '')}>
            <span className="glyphicon glyphicon-heart"></span>
          </button>
        </div>


        <div className="carpic-btn-group">
          {listImageGroup}
        </div>

        <div className="col-xs-12 detail-info">
          <p className="title-info">
            {this.props.item.title}
            <span>
              起拍价 :
              <span className="price">{this.props.item.start_price}</span>
            </span>
          </p>
          <div className="labels">
            {adwordItems}
          </div>
        </div>
      </div>
    )
  }
}
// detail slider end





// car reports
const pics = ['/img/rz2.jpg', '/img/rz1.jpg'];
const reportPics = pics.map((pic, i) => <div key={i}>
  <img className="img-responsive" src={pic} alt="CarReport"/>
</div>);
class CarReport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }
  loadData() {
    $.get(CBH.apiRoot+'/?g=Api&m=Carport&a=carreport_edit&gid=' + this.props.gid + '&cid=' + this.props.cpid + '&uv=1&type=jsonp', function(res) {
      this.setState(res)
    }.bind(this), 'jsonp');
  }
  render() {
    let items = this.state.data.map((item, i) => <li key={i}>
      <span className="item-name">{item.name}
        :
      </span>
      <span className="item-name-info">{item.comment[0].type == 'date'
          ? item.comment[0].value
          : (item.comment[0].type == 'city'
            ? item.comment[0].value.prov + ' ' + item.comment[0].value.city
            : (item.comment[0].type == 'text'
              ? (item.comment[0].type == 'img'?'':item.comment[0].value)
              : ''))}</span>
    </li>);
    return (
      <div className="item panel panel-default">
        <div className="panel-heading" onClick={this.loadData.bind(this)}>{this.props.title}</div>
        <ul className="panel-body">
          {items}
        </ul>
      </div>
    );
  }
}
class CarReportGroup extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    }
  }
  componentWillMount() {
    $.get(CBH.apiRoot+'/?g=Api&m=Carport&a=kvgroup&type=jsonp', function(res) {
      this.setState(res);
    }.bind(this), 'jsonp');
  }
  render() {
    let groups = this.state.data.map((groupItem, i) => <CarReport ref="cr1" key={i} gid={groupItem.id} cpid={this.props.cpid} title={groupItem.title}/>);
    return (
      <div className="car-report">
        <div className="report-title">
          <span>检测报告</span>
          <span>注 : 此报告由专业第三方检测机构 －－ 中车提供</span>
        </div>
        <p className="mNotice">* 点击标题可展开详情
        </p>
        {groups}
        <div className="report-block">
          {/* reportPics*/}
        </div>
      </div>
    );
  }
}
// car reports end
class Detail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      status: 0
    };
  }
  componentWillMount() {}
  componentDidMount() {
    $.get(CBH.apiRoot + "/?g=Api&m=CommonProduct&a=product&id=" + this.props.params.id + "&uid=" + CBH.UserInfo.id, function(result) {
      this.setState(result);
    }.bind(this), 'jsonp');
    function progress(timeleft, timetotal, $element) {
      var progressBarWidth = timeleft * $element.width() / timetotal;
      $element.find('div').animate({
        width: progressBarWidth
      }, 500).html();
      if (timeleft > 0) {
        setTimeout(function() {
          progress(timeleft - 1, timetotal, $element);
        }, 1000);
      }
    }
    $(document).ready(function() {
      progress(10, 10, $('#progressBar'));
    });
  }

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="detail-block">
            <DetailSlider ishave={this.state.status} liked={this.state.data.uid && this.state.data.uid != ''} item={this.state.data}/>
              {/* <NowAuction /> */}
            <CarReportGroup cpid={this.state.data.cpid}/>
          </div>
        </div>
      </div>
    );
  }
}
export default Detail;
